# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : token_view.py
# Time       ：2023/7/9 16:49
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    token 视图
    token views
"""
from flask import request
from flask_restx import fields

from apis.system_oauth.models import SystemUser
from apis.token import token_ns
from conf.config import FlaskConfig
from public.api_utils.api_decorator import handle_api_error
from public.base_response import generate_response, MarshalModel
from public.api_utils.jwt_utils import JWTUtils
from public.base_view import AbstractView

oauth_token = {
    'login_type': fields.String(description='登录方式， username,email,iphone', required=True),
    'username': fields.String(description='用户名称', required=True),
    'password': fields.String(description='用户密码', required=True),
}
token_response = {'token': fields.String()}

token_marshal = MarshalModel('token', token_ns)


class TokenView(AbstractView):
    url = '/'

    def __init__(self, *args, **kwargs):
        super(TokenView, self).__init__(*args, **kwargs)
        self.form_data = request.json
        self.jwt_utils = JWTUtils()
        self.login_types = {
            'username': self.form_data.get('username'),
            'email': self.form_data.get('email'),
            'phone': self.form_data.get('phone'),
        }
        self.login_type = self.form_data.get('login_type') or 'username'

    def generate_payload(self):
        login_value = self.form_data.get(self.login_type)
        password = self.form_data.get('password')
        SystemUser.check_password(password, self.login_type, login_value)
        return {
            'login_type': self.login_type,
            'login_value': login_value,
            'password': password
        }

    @handle_api_error()
    @token_ns.expect(token_marshal.detail_request(oauth_token))
    @token_ns.marshal_with(token_marshal.detail_response(token_response, is_db=False))
    def post(self):
        """获取token"""
        pay_load = self.generate_payload()
        token = self.jwt_utils.generate_token(pay_load, expiry=FlaskConfig.EXPIRY)
        print(token)
        return generate_response({'token': token})
